#include "historyproduct.h"
#include <QJsonObject>
#include "dbhelper.h"

HistoryProduct::HistoryProduct(QObject *parent) : QObject(parent)
{
    product = nullptr;
}

void HistoryProduct::loadFromJsonObject(QJsonObject obj){
    id = obj.value("id").toInt();
    type = obj.value("type").toInt();
    sourceCompanyId = obj.value("source_company_id").toString();
    targetCompanyId = obj.value("target_company_id").toString();
    sourceProductId = obj.value("source_product_id").toString();
    targetProductId = obj.value("target_product_id").toString();
    sourceScale = obj.value("source_scale").toInt();
    targetScale = obj.value("target_scale").toInt();
    historyPrice = obj.value("history_price").toDouble();
}

Product* HistoryProduct::getProduct(){
    if(product==nullptr){
        DbHelper helper;
        product = helper.getProductById(sourceProductId);
    }

    return product;
}

QString HistoryProduct::toJson(){
    QString jsonStr = "{";

    jsonStr.append("\"id\":"+QString("%1").arg(id)+",");
    jsonStr.append("\"type\":"+QString("%1").arg(type)+",");
    jsonStr.append("\"source_company_id\":"+Tools::toJsonStr(sourceCompanyId)+",");
    jsonStr.append("\"target_company_id\":"+Tools::toJsonStr(targetCompanyId)+",");
    jsonStr.append("\"source_product_id\":"+Tools::toJsonStr(sourceProductId)+",");
    jsonStr.append("\"target_product_id\":"+Tools::toJsonStr(targetProductId)+",");
    jsonStr.append("\"source_scale\":"+QString("%1").arg(sourceScale)+",");
    jsonStr.append("\"target_scale\":"+QString("%1").arg(targetScale)+",");
    jsonStr.append("\"history_price\":"+QString("%1").arg(historyPrice));

    return jsonStr.append("}");
}
